<template>
  <a-card :bordered='false' :class="'cust-erp-sub-tab'">
    <!-- 操作按钮区域 -->
    <div v-if='mainId' class='table-operator'>
      <a-button v-show='!isChecked' icon='plus' type='primary' @click='handleAdd'>新增物料</a-button>
      <a-button v-show='!isChecked' icon='plus' type='primary' @click='handleBatchAdd'>批量添加物料</a-button>
      <a-button
        v-show='!isChecked && !saveBatchMaterial'
        icon='save'
        style='background-color: #67c23a;border-color: #67c23a'
        type='primary'
        @click='handleSaveMaterial'
      >保存全部物料
      </a-button>
      <a-button v-show='!isChecked' icon='plus' type='primary' @click='handleOpenDeliveryDateListModal(true)'
      >添加日期序列
      </a-button>
      <a-button v-show='!isChecked' icon='swap' type='primary' @click='handleOpenDeliveryDateListModal(false)'
      >替换日期序列
      </a-button>
      <a-button v-show='!isChecked' icon='delete' type='primary' @click='handleOpenDateListTreeModal()'
      >删除日期序列
      </a-button>
      <a-tooltip title='选择下方的物料后，点击生成销售出库单'>
        <a-button v-if='!editable' v-show='isChecked' type='primary' @click='generateSaleOut'>生成销售出库单</a-button>
      </a-tooltip>
      <a-tooltip title='选择下方的物料后，点击生成生产任务单'>
        <a-button v-if='!editable' v-show='isChecked' type='primary' @click='generateMission'>生成生产任务单</a-button>
      </a-tooltip>
      <a-button v-if='!editable' v-show='!isChecked' icon='edit' type='primary' @click='handleEditNumber'
      >编辑全部数量
      </a-button>
      <a-button
        v-else
        icon='save'
        style='background-color: #67c23a;border-color: #67c23a'
        type='primary'
        @click='handleSaveNumber'
      >保存全部数量
      </a-button>
      <a-dropdown v-if='selectedRowKeys.length > 0 && !isChecked'>
        <a-menu slot='overlay'>
          <a-menu-item key='1' @click='batchDel'>
            <a-icon type='delete' />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style='margin-left: 8px'>
          批量操作
          <a-icon type='down' />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择
        <a style='font-weight: 600'>{{ selectedRowKeys.length }}</a
        >项
        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>
      </div>

      <a-table
        ref='table'
        :columns='columns'
        :dataSource='dataSource'
        :loading='loading'
        :pagination='ipagination'
        :rowSelection='{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }'
        :scroll='{ x: true }'
        bordered
        rowKey='id'
        size='middle'
        @change='handleTableChange'
        @keyup.enter.native='handleSaveNumber'
      >
        <template slot='materialCode' slot-scope='text, record'>
          <div>
            <HfMaterialSearchSelectTag
              v-if='record.editable'
              v-model='record.materialCode'
              :data-url='url.materialList'
              :extra-param='{ customId: customId }'
              @change='onMaterialChange(arguments, record)'
            ></HfMaterialSearchSelectTag>
            <template v-else slot-scope='text, record'>
              {{ record.materialCode }}
            </template>
          </div>
        </template>
        <template slot='action' slot-scope='text, record'>
          <div v-show='record.status !== 1' class='editable-row-operations'>
            <span v-if='record.editable'>
              <a @click='() => save(record)'>保存</a>
              <a-divider style='background-color: grey' type='vertical'></a-divider>
              <a @click='() => cancel(record)'>取消</a>
            </span>
            <span v-else>
              <a v-show='!isChecked' :disabled='editable' @click='edit(record)'>编辑</a>
              <a-divider v-show='!isChecked' style='background-color: grey' type='vertical'></a-divider>
              <a v-show='!isChecked' :disabled='editable' @click='handleDelete(record.id)'>删除</a>
            </span>
          </div>
        </template>
        <template v-for='slot in numberSlots' :slot='slot' slot-scope='text, record'>
          <a-input-number v-if='record.selectable || editable' v-model:value='record[slot].number' :min='0' style='' />
          <span v-else>{{ record[slot].number }}</span>
        </template>
        <template slot='number'>
          <a-tooltip title='预期交货的总数量'>
            总数
          </a-tooltip>
        </template>
        <template slot='totalPrice'>
          <a-tooltip title='预计总价税合计=预计交货数量 * 含税单价'>
            价税合计
          </a-tooltip>
        </template>
      </a-table>
    </div>

    <HfAddDeliveryDateList
      ref='hfAddDeliveryDateList'
      @onDateListChange='handleDateListChange(arguments)'
    ></HfAddDeliveryDateList>
    <HfDeliveryDateListTreeModal
      ref='HfDeliveryDateListTreeModalRef'
      @onChange='handleDateListDeleteChange'
    ></HfDeliveryDateListTreeModal>
    <hf-generate-sale-out-modal
      ref='hfGenerateSaleOutModal'
      :customId='customId'
      :customOrderSerial='customOrderSerial'
      :sourceId='mainId'
      :sourceSerial='sourceSerial'
      @generateSaleOutOk='searchReset'
    ></hf-generate-sale-out-modal>
    <GenerateMissionModal
      ref='GenerateMissionRef'
      :sourceId='mainId'
      :sourceSerial='sourceSerial'
      @ok='searchReset'
    ></GenerateMissionModal>
    <HfBatchAddSaleOrderDetail ref='hfBatchAddSaleOrderDetailRef' @ok='handleBatchAddOk' />
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { HfOrderDetailMixin } from '@/mixins/HfOrderDetailMixin'
import { getAction, postAction } from '@api/manage'
import HfAddDeliveryDateList from '@views/sale/modules/HfAddDeliveryDateList.vue'
import HfGenerateSaleOutModal from '@views/sale/modules/HfGenerateSaleOutModal.vue'
import HfSaleOrderChart from '@views/sale/charts/HfSaleOrderChart.vue'
import HfDeliveryDateListTreeModal from '@views/sale/modules/HfDeliveryDateListTreeModal.vue'
import HfMaterialSearchSelectTag from '@comp/HfManual/HfMaterialSearchSelectTag.vue'
import GenerateMissionModal from '@views/sale/modules/GenerateMissionModal.vue'
import HfBatchAddSaleOrderDetail from '@views/sale/modules/HfBatchAddSaleOrderDetail.vue'

export default {
  name: 'HfSaleOrderDetailList',
  mixins: [JeecgListMixin, HfOrderDetailMixin],
  components: {
    HfBatchAddSaleOrderDetail,
    GenerateMissionModal,
    HfMaterialSearchSelectTag,
    HfDeliveryDateListTreeModal,
    HfSaleOrderChart,
    HfGenerateSaleOutModal,
    HfAddDeliveryDateList
  },
  props: {
    mainId: {
      type: String,
      default: '',
      required: false
    },
    customId: {
      type: String,
      default: '',
      required: false
    },
    customOrderSerial: {
      type: String,
      default: '',
      required: false
    },
    sourceSerial: {
      type: String,
      default: '',
      required: false
    }
  },
  watch: {
    mainId: {
      immediate: true,
      handler(val) {
        if (!this.mainId) {
          this.clearList()
        } else {
          this.queryParam['sourceId'] = val
          this.loadData(1)
        }
      }
    }
  },
  data() {
    return {
      description: '销售订单管理页面',
      disableMixinCreated: true,
      isChecked: false,
      editable: false,
      // 表头
      columnsDefault: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          },
          width: 40,
          fixed: 'left'
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode',
          scopedSlots: { customRender: 'materialCode' },
          width: 100,
          fixed: 'left'
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType_dictText'
        },
        {
          title: '单箱数',
          align: 'center',
          dataIndex: 'perNumber'
        },
        {
          align: 'center',
          dataIndex: 'number',
          scopedSlots: { title: 'number' },
          customRender: (t)=>{
            return t===null?0:t
          }
        },
        {
          title: '单价',
          align: 'center',
          dataIndex: 'price',
          customRender: function(t) {
            return '￥' + t
          }
        },
        {
          title: '含税单价',
          align: 'center',
          dataIndex: 'taxPrice',
          customRender: function(t) {
            return '￥' + t
          }
        },
        {
          title: '税率',
          align: 'center',
          dataIndex: 'tax',
          customRender: function(t) {
            return t + '%'
          }
        },
        {
          align: 'center',
          dataIndex: 'totalPrice',
          slots: { title: 'totalPrice' },
          customRender: function(t) {
            t = t === null ? 0 : t
            return '￥' + t
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      columns: [],
      url: {
        list: '/sale/hfSaleOrder/listHfSaleOrderDetailByMainId',
        delete: '/sale/hfSaleOrder/deleteHfSaleOrderDetail',
        deleteBatch: '/sale/hfSaleOrder/deleteBatchHfSaleOrderDetail',
        materialList: '/sale/hfSalePrice/getSalePriceByCustom',
        add: '/sale/hfSaleOrder/addHfSaleOrderDetail',
        edit: '/sale/hfSaleOrder/editHfSaleOrderDetail',
        addBatchHfSaleOrderDetail: '/sale/hfSaleOrder/addBatchHfSaleOrderDetail',
        editBatchOrderDetailNumber: '/sale/hfSaleOrder/editBatchOrderDetailNumber',
        addDeliverySchedule: '/sale/hfSaleOrder/addDeliverySchedule',
        replaceDeliverySchedule: '/sale/hfSaleOrder/replaceDeliverySchedule',
        deleteDeliverySchedule: '/sale/hfSaleOrder/deleteDeliverySchedule'
      },
      numberSlots: [],
      saleOutSlots: []
    }
  },
  created() {
    this.columns = JSON.parse(JSON.stringify(this.columnsDefault))
  },
  mounted() {
  },
  computed: {
    saveBatchMaterial() {
      return this.dataSource.every(item => item.id)
    }
  },
  methods: {
    clearList() {
      this.dataSource = []
      this.selectedRowKeys = []
      this.ipagination.current = 1
    },
    handleOpenDateListTreeModal() {
      if (this.dataSource.length === 0) {
        this.$message.warning('请先添加销售订单明细')
        return
      }
      this.$refs.HfDeliveryDateListTreeModalRef.visible = true
      this.$refs.HfDeliveryDateListTreeModalRef.loadData(this.dataSource.at(-1)['dateList'])
    },
    handleDateListDeleteChange(dateList) {
      this.loading = true
      let param = []
      dateList.forEach(item => {
        this.dataSource.forEach(data => param.push(data[item].id))
      })

      postAction(this.url.deleteDeliverySchedule, param)
        .then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.loadData()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleOpenDeliveryDateListModal(bool) {
      if (this.dataSource.length === 0) {
        this.$message.warning('请先添加销售订单明细')
        return
      }

      this.$refs.hfAddDeliveryDateList.visible = true
      this.$refs.hfAddDeliveryDateList.add = bool
    },
    handleDateListChange([dateList, add]) {
      let param = {
        idList: this.dataSource.map(item => item.id),
        dateList: dateList,
        saleOrderId: this.mainId
      }
      this.loading = true
      postAction(add ? this.url.addDeliverySchedule : this.url.replaceDeliverySchedule, param)
        .then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.loadData()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    onMaterialChange([value, record], tableRow) {
      // 初始化数据
      Object.assign(tableRow, {
        materialId: record.materialId,
        materialCode: record.materialCode,
        materialName: record.materialName,
        sap: record.sap,
        unit: record.unit,
        unit_dictText: record.unit_dictText,
        materialType: record.materialType,
        materialType_dictText: record.materialType_dictText,
        perNumber: record.perNumber,
        warehouse: record.warehouse,
        warehouse_dictText: record.warehouse_dictText,
        price: record.price,
        tax: record.tax,
        taxPrice: record.taxPrice,
        saleOutTotalPrice: 0.0,
        totalPrice: 0.0
      })
    },
    edit(record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.id === record.id)
      if (target) {
        target.editable = true
        target.selectable = true
        this.selectValue = target.materialCode
        this.dataSource = newData
      }
    },
    handleAdd() {
      this.saveMaterial = true
      let temp = { add: true, selectable: true, editable: true }
      this.dataSource.unshift(temp)
    },
    save(record) {
      // 检查是否已存在
      if (this.dataSource.filter(item => record.materialId === item.materialId).length > 1) {
        this.$message.warning(`${record.materialCode}该物料已存在`)
        return
      }
      this.loading = false
      let param = Object.assign({}, record)
      if (param.add) {
        param['sourceId'] = this.mainId
        param['sourceSerial'] = this.sourceSerial
        postAction(this.url.add, param)
          .then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = true
            this.selectValue = ''
          })
      } else {
        param['sourceId'] = this.mainId
        param['sourceSerial'] = this.sourceSerial
        let model = {
          hfSaleOrderDetail: param,
          scheduleList: param.dateList.map(item => {
            return param[item]
          })
        }
        postAction(this.url.edit, model)
          .then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = true
            this.selectValue = ''
          })
      }
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let params = this.getQueryParams() //查询条件
      this.loading = true
      getAction(this.url.list, params)
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            // 重置列，防止一直添加
            this.columns = []
            let columns = [...this.columnsDefault]
            // “数量”的slot名
            this.numberSlots = []
            // 根据日期序列去更新表格列
            if (this.dataSource[0] && this.dataSource[0]['dateList'].length > 0) {
              let temp = this.dataSource[0]['dateList']
              let column = {}
              let sortColumn = []
              // 组装成a-table所需要的表头分组格式，即每个column需要有一个children属性且它的值是数组
              for (const item of temp) {
                let numberDataIndex = item
                this.numberSlots.push(numberDataIndex)
                column = {
                  title: item,
                  align: 'center',
                  dataIndex: this.dataSource[item],
                  scopedSlots: { customRender: numberDataIndex }
                }
                // 插入倒数一个位置
                sortColumn.splice(this.columns.length - 1, 0, column)
              }
              // 排序一下
              sortColumn.sort((a, b) => {
                const dateA = new Date(a.title)
                const dateB = new Date(b.title)
                return dateA - dateB
              })
              sortColumn.forEach(item => {
                columns.splice(columns.length - 1, 0, item)
              })
              // 如果是审核页面，就不显示操作列
              if (this.isChecked) {
                columns.pop()
              }
              // 更新显示的列
              this.columns = columns
            }
            // 如果一条数据都没有，显示默认列
            else {
              this.columns = this.columnsDefault
            }
            // 分页
            if (res.result.total) {
              if (res.result.total === res.result.size) {
                this.ipagination.showSizeChanger = false
              }
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleEditNumber() {
      if (this.dataSource.length === 0) {
        this.$message.warning('请先添加至少一条明细')
        return
      }
      this.editable = true
    },
    handleSaveNumber() {
      this.editable = false
      let scheduleList = []
      let dateList = this.dataSource.at(-1)['dateList']
      this.dataSource.forEach(item => {
        dateList.forEach(date => {
          scheduleList.push({
            id: item[date].id,
            number: item[date].number,
            saleOrderDetailId: item.id
          })
        })
      })

      postAction(this.url.editBatchOrderDetailNumber, scheduleList).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    generateSaleOut() {
      if (this.selectionRows.length === 0) {
        this.$message.warning('请选择要生成销售出库单的数据')
        return
      }
      this.$refs.hfGenerateSaleOutModal.visible = true
      this.$refs.hfGenerateSaleOutModal.loadData(this.selectionRows)
    },
    generateMission() {
      if (this.selectionRows.length === 0) {
        this.$message.warning('请选择要生成生产任务单的数据')
        return
      }

      this.$refs.GenerateMissionRef.visible = true
      // console.log('this.$refs.GenerateMissionRef',this.$refs.GenerateMissionRef)
      this.$refs.GenerateMissionRef.loadData(this.selectionRows)
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    handleSaveMaterial() {
      let param = this.dataSource.filter(item => !item.id)

      param.forEach(item => {
        item['sourceId'] = this.mainId
        item['sourceSerial'] = this.sourceSerial
      })

      this.loading = true
      postAction(this.url.addBatchHfSaleOrderDetail, param)
        .then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.loadData()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleBatchAdd() {
      this.$refs.hfBatchAddSaleOrderDetailRef.visible = true
      this.$refs.hfBatchAddSaleOrderDetailRef.sourceId = this.mainId
      this.$refs.hfBatchAddSaleOrderDetailRef.sourceSerial = this.sourceSerial
      this.$refs.hfBatchAddSaleOrderDetailRef.queryParam.customId = this.customId
      this.$refs.hfBatchAddSaleOrderDetailRef.loadData()
    },
    handleBatchAddOk() {
      this.loadData()
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
